<template>
  <div class="app-container">
    <el-row :gutter="12">
      <el-col :span="24" class="p-b-5">
        <el-card shadow="always">
          <div class="flex flex-wrap">
            <div class="flex justify-between w-full p-b-5">
              <div class="font-black text-xl">培训业务分类</div>
              <el-row :gutter="10">
                <el-col :span="7">
                  <el-date-picker
                    style="width: 100%"
                    v-model="industryParams.dateArr"
                    type="daterange"
                    range-separator="-"
                    value-format="YYYY-MM-DD"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    @change="getIndustry"
                  />
                </el-col>
                <el-col :span="7">
                  <el-select
                    class="w-full"
                    v-model="industryParams.fiscalStatementType"
                    placeholder="报表类型"
                    @change="getIndustry"
                  >
                    <el-option
                      v-for="item in fiscal_statement_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    /> </el-select
                ></el-col>
                <el-col :span="7">
                  <el-select
                    class="w-full"
                    v-model="industryParams.isTax"
                    placeholder="是否含税"
                    @change="getIndustry"
                  >
                    <el-option
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    /> </el-select
                ></el-col>
                <el-col :span="3" class="text-right">
                  <el-button
                    icon="Download"
                    @click="exportExcel('培训业务分类')"
                    >导出</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div class="h-300px w-3/6">
              <EcharsPie :pieObj="pieObj" />
            </div>
            <div class="w-3/6">
              <el-table
                ref="industryTable"
                :data="tableData"
                style="width: 100%"
                border
                stripe
                @row-click="rowClick"
                show-summary
                :sum-text="'统计'"
              >
                <el-table-column prop="businessType" label="名称">
                  <template #default="scope">
                    <dict-drop
                      :options="order_business_type"
                      :value="scope.row.businessType"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="totalPrice" label="订单金额(元)" />
                <el-table-column prop="percentage" label="新增占比(%)" />
                <el-table-column
                  type="index"
                  label="排名"
                  align="center"
                  width="60"
                />
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" class="p-b-5">
        <el-card shadow="always">
          <div class="flex flex-wrap">
            <div class="flex justify-between w-full p-b-5">
              <div class="font-black text-xl">地市统计分析</div>
              <el-row :gutter="10">
                <el-col :span="7">
                  <el-date-picker
                    style="width: 100%"
                    v-model="levelParams.dateArr"
                    type="daterange"
                    range-separator="-"
                    value-format="YYYY-MM-DD"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    @change="getLevel"
                  />
                </el-col>
                <el-col :span="7">
                  <el-select
                    class="w-full"
                    v-model="levelParams.fiscalStatementType"
                    placeholder="报表类型"
                    @change="getLevel"
                  >
                    <el-option
                      v-for="item in fiscal_statement_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    /> </el-select
                ></el-col>
                <el-col :span="7">
                  <el-select
                    class="w-full"
                    v-model="levelParams.isTax"
                    placeholder="是否含税"
                    @change="getLevel"
                  >
                    <el-option
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    /> </el-select
                ></el-col>
                <el-col :span="3" class="text-right">
                  <el-button
                    icon="Download"
                    @click="exportExcel('地市统计分析')"
                    >导出</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div class="min-h-300px w-full">
              <el-table
                ref="levelTable"
                :data="tableLevelData"
                style="width: 100%"
                border
                stripe
                @cell-click="cellClick"
                show-summary
                :sum-text="'统计'"
              >
                <el-table-column
                  type="index"
                  label="排名"
                  align="center"
                  width="60"
                />
                <el-table-column prop="deptId" label="地区">
                  <template #default="scope">
                    <dict-drop
                      :options="bidding_unit"
                      :value="scope.row.deptId"
                    ></dict-drop>
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in tableLevel"
                  :key="index"
                  v-bind="item"
                />
                <el-table-column
                  prop="percentage"
                  label="销售占比"
                  min-width="100"
                >
                  <template #default="scope">
                    <span
                      class="inline-block w-4/6 bg-slate-100 h-10px rounded-full overflow-hidden"
                    >
                      <span
                        class="inline-block bg-sky-300 h-10px align-top"
                        :style="{ width: `${scope.row.percentage}%` }"
                      ></span>
                    </span>
                    {{ scope.row.percentage }}%</template
                  >
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" class="p-b-5">
        <el-card shadow="always">
          <div class="flex flex-wrap">
            <div class="flex justify-between w-full p-b-5">
              <div v-if="orderBusinessType.length > 0">
                <el-radio-group
                  v-model="additionalParams.businessType"
                  class="groupBtn"
                  @change="getAdditional"
                >
                  <el-radio
                    v-for="(item, index) in orderBusinessType"
                    :key="index"
                    :label="item.value"
                    border
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </div>
              <div>
                <el-radio-group
                  v-model="additionalParams.dateType"
                  @change="getAdditional"
                >
                  <el-radio-button label="1">近7天</el-radio-button>
                  <el-radio-button label="2">近30天</el-radio-button>
                  <el-radio-button label="3">近90天</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="h-360px w-full">
              <EcharsLine :lineObj="lineObj" />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" class="p-b-5">
        <el-card shadow="always">
          <div class="flex flex-wrap">
            <div class="flex justify-between w-full p-b-5">
              <div class="font-black text-xl">服务到期人数分析</div>
              <el-row :gutter="10" class="min-w-12/24 text-right justify-end">
                <el-col :span="8">
                  <el-radio-group
                    v-model="expireParams.dateType"
                    @change="getExpire"
                  >
                    <el-radio-button label="1">本周</el-radio-button>
                    <el-radio-button label="2">本月</el-radio-button>
                    <el-radio-button label="3">3月内</el-radio-button>
                  </el-radio-group></el-col
                >
                <el-col :span="3" class="text-right">
                  <el-button
                    icon="Download"
                    @click="exportExcel('服务到期人数分析')"
                    >导出</el-button
                  >
                </el-col>
              </el-row>
            </div>
            <div class="min-h-300px w-full">
              <el-table
                ref="expireTable"
                :data="expireData"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="deptId" label="地区">
                  <template #default="scope">
                    <dict-drop
                      :options="bidding_unit"
                      :value="scope.row.deptId"
                    ></dict-drop>
                  </template>
                </el-table-column>
                <el-table-column prop="certificateNum" label="证书" />
                <el-table-column
                  prop="educationPromotionNum"
                  label="学历提升"
                />
                <el-table-column prop="memberNum" label="会员" />
                <el-table-column prop="totalNum" label="总人数" />
                <el-table-column label="操作" align="center" v-if="showColu">
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['system:notice:edit']"
                    >
                      <template #icon>
                        <span
                          class="i-fluent-chevron-circle-right-12-filled"
                        ></span>
                      </template>
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup name="IndustryStatistics">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import EcharsPie from './modules/pie'
import EcharsLine from './modules/line'
import { businessTypeOption, order_business_type } from '@/hooks/dict/order'
import {
  statisticsAdditional,
  statisticsLevel,
  statisticsIndustry,
  statisticsExpire
} from '@/api/industryStatistics/index'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
const components = shallowRef({
  EcharsPie,
  EcharsLine
})
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const {
  bidding_unit, //内部单位
  yes_or_no, //是否
  fiscal_statement_type //是否
} = proxy.useDict('bidding_unit', 'yes_or_no', 'fiscal_statement_type')
const data = reactive({
  industryParams: {
    dateArr: []
  },
  pieObj: {},
  // pieOption: {
  //   tooltip: {
  //     trigger: 'item'
  //   },
  //   legend: {
  //     orient: 'horizontal',
  //     bottom: '0'
  //   },
  //   series: [
  //     {
  //       name: 'Access From',
  //       type: 'pie',
  //       radius: '50%',
  //       data: [
  //         { value: 42.71, name: 'Search' },
  //         { value: 42.71, name: 'Direct' },
  //         { value: 21.08, name: 'Email' },
  //         { value: 21.08, name: 'Union Ads' },
  //         { value: 2.1, name: 'Video Ads' },
  //         { value: 0.39, name: 'Video ' }
  //       ],
  //       emphasis: {
  //         itemStyle: {
  //           shadowBlur: 10,
  //           shadowOffsetX: 0,
  //           shadowColor: 'rgba(0, 0, 0, 0.5)'
  //         }
  //       }
  //     }
  //   ]
  // },
  tableData: [],

  levelParams: {
    dateArr: []
  },
  tableLevelData: [],

  orderBusinessType: [],
  additionalParams: {
    businessType: '培训产业-继续教育',
    dateType: '1'
  },
  lineObj: {},

  expireParams: {
    dateType: '1'
  },
  expireData: []
})
let {
  industryParams,
  pieObj,
  tableData,
  levelParams,
  tableLevelData,
  orderBusinessType,
  additionalParams,
  lineObj,
  expireParams,
  expireData
} = toRefs(data)

watchEffect(
  () => {
    if (order_business_type.value.length > 0) {
      let types = toRaw(order_business_type.value)
      orderBusinessType.value = types.filter(e => e.parentId == '财税-培训产业')
      // console.log('orderBusinessType.value', orderBusinessType.value)
    }
  },
  { flush: 'post' }
)
function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 点击培训业务分类行
function rowClick(row, column, event) {
  let obj = {
    receiptsDates: industryParams.value.dateArr,
    businessType: row.businessType
  }
  // console.log('obj==>', obj)
  goTo('/sales/indent/salesOrder', { salesOrderData: JSON.stringify(obj) })
}
// 点击地市统计分析单元格
function cellClick(row, column, cell, event) {
  let levetKey = tableLevel.value.filter(e => e.prop == column.property)
  if (levetKey.length == 0) return
  let obj = {
    deptId: row.deptId,
    receiptsDates: levelParams.value.dateArr,
    businessType: levetKey[0].dictValue
  }
  console.log('obj==>', obj)
  goTo('/sales/indent/salesOrder', { salesOrderData: JSON.stringify(obj) })
}
// 培训业务分类
function getIndustry() {
  statisticsIndustry(industryParams.value).then(ref => {
    let pieData = ref.data.map(e => {
      return {
        value: e.percentage,
        name: e.businessType.replace('培训产业-', '')
      }
    })
    pieObj.value.data = pieData
    tableData.value = ref.data
  })
}
getIndustry()

const tableLevel = ref([
  {
    show: true,
    prop: 'contractOrderNumber',
    label: '合同(订单)编号',
    align: 'center',
    width: 160,
    showOverflowTooltip: true
  }
])
// 地市分析
function getLevel() {
  statisticsLevel(levelParams.value).then(ref => {
    tableLevelData.value = ref.data.data
    tableLevel.value = ref.data.label.map(item => {
      return {
        show: true,
        prop: item.key,
        label: item.dictLabel,
        dictValue: item.dictValue,
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    })

    // console.log('ref==>', ref)
  })
}
getLevel()

// 新增人数
function getAdditional() {
  statisticsAdditional(additionalParams.value).then(ref => {
    // tableAdditionalData.value = ref.data
    lineObj.value.title = '新增人数'
    lineObj.value.data = ref.data.map(e => {
      return {
        name: e.date,
        value: e.num
      }
    })
  })
}
getAdditional()

// 服务到期人数
function getExpire() {
  statisticsExpire(expireParams.value).then(ref => {
    expireData.value = ref.data
  })
}
getExpire()

const showColu = ref(true)
// 前端导出excel
const exportExcel = excelName => {
  let tableBox = {
    expireTable: '服务到期人数分析',
    levelTable: '地市统计分析',
    industryTable: '培训业务分类'
  }
  let tableRef = ''
  for (let key in tableBox) {
    console.log('导出key==>', key)
    if (tableBox[key] === excelName) {
      tableRef = key
    }
  }
  showColu.value = false
  setTimeout(() => {
    try {
      const $e = proxy.$refs[tableRef].$el
      let $table = $e.querySelector('.el-table__fixed')
      if (!$table) {
        $table = $e
      }

      const wb = XLSX.utils.table_to_book($table, { raw: true })
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${excelName}.xlsx`
      )
      showColu.value = true
    } catch (e) {
      showColu.value = true
      if (typeof console !== 'undefined') console.error(e)
    }
  }, 500)
}
</script>
<style lang="scss" scoped>
.el-radio-group.groupBtn :deep(.el-radio__input) {
  display: none;
}
</style>
